import {
  ArgumentsHost,
  CallHandler,
  Catch,
  ExceptionFilter,
  HttpException,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { map, Observable } from 'rxjs';
import { ExecutionContext } from '@nestjs/common/interfaces/features/execution-context.interface';
import { Request, Response } from 'express';
import * as moment from 'moment';

interface Data<T> {
  data: T;
}

// 全局响应拦截器：返回格式化数据
@Catch()
export class ExceptionFilters<T> implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost): any {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    // 确保异常存在
    if (!exception) {
      response.status(500).json({
        status: 500,
        msg: 'Internal Server Error',
        data: {
          time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          success: false,
          path: request.url,
        },
      });
      return;
    }

    console.error();
    // 设置HTTP状态码
    const status = exception.getStatus ? exception.getStatus() : 500;

    // 构造响应体
    response.status(status).json({
      status,
      msg: exception.message || 'Internal Server Error', // 使用异常消息或默认消息
      data: {
        time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        success: false,
        path: request.url,
      },
    });
  }
}
